﻿#region

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using LocalNugetUpdate.Model;
using LocalNugetUpdate.Model.NupkgModelJsonTypes;
using Newtonsoft.Json;
using SharpCompress.Archives;
using wsy.ext.Devlib.ExtensionMethods;

#endregion

namespace LocalNugetUpdate.BAL.Mehtod
{
    public class GetNupkgInfo
    {
        public GetNupkgInfo(string pStrPath)
        {
            MStrPath = pStrPath;
            MMetadatas = new List<Metadata>();
        }

        private void GetNupkgPaths()
        {
            MStrNupkgPaths = Directory.GetFiles(MStrPath, "*.nupkg");
        }

        private NupkgModel GetIt(string pStrFilePath)
        {
            var archive = ArchiveFactory.Open(pStrFilePath);
            var nuspec = archive.Entries.First(s => s.Key.EndsWith(".nuspec"));
            if (nuspec == null) return null;
            StreamReader sr = new StreamReader(nuspec.OpenEntryStream());
            string text = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(text);
            string strxml = JsonConvert.SerializeXmlNode(xml);
            return JsonConvert.DeserializeObject<NupkgModel>(strxml);
        }

        public async Task<GetNupkgInfo> GetPackages()
        {
            GetNupkgPaths();
            await MStrNupkgPaths.TasksEachDo(GetOnePackage, 100);
            return this;
        }

        public Task GetOnePackage(string path)
        {
            return Task.Run(() =>
            {
                lock (MMetadatas)
                {
                    MMetadatas.Add(GetIt(path).Package.Metadata);
                }
            });
        }

        #region

        private string[] MStrNupkgPaths { get; set; }
        private string MStrPath { get; }
        public List<Metadata> MMetadatas { get; set; }

        #endregion
    }
}